package com.github.ghsea.framework.job.core.client;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import com.caucho.hessian.client.HessianProxyFactory;
import com.github.ghsea.framework.job.api.JobExecutor;
import com.github.ghsea.framework.job.common.Endpoint;
import com.github.ghsea.framework.job.common.JobExecuteResult;
import com.github.ghsea.framework.job.common.JobExecutorParams;

public class JobExecutorClient implements JobExecutor {

	private JobClientLocator clientLocator;

	private HessianProxyFactory factory = new HessianProxyFactory();

	private final String HESSIAN_ROOT_URL = "/jobExectuor";
	// TODO 从注册中心取

	private static Map<String, JobExecutorClient> app2Client = new HashMap<String, JobExecutorClient>();

	private static Object lock = new Object();

	private String appName;

	private JobExecutorClient(String appName) {
		this.appName = appName;
		this.clientLocator = new JobClientLocator(appName);
	}

	public static JobExecutorClient getInstance(String appName) {
		JobExecutorClient locator = app2Client.get(appName);
		if (locator == null) {
			synchronized (lock) {
				if (locator == null) {
					locator = new JobExecutorClient(appName);
					app2Client.put(appName, locator);
				}
			}
		}

		return locator;
	}

	@Override
	public JobExecuteResult execute(JobExecutorParams exeParams) {

		// TODO retry && timeout
		Endpoint serverEndPoint = clientLocator.select();
		String serverUrl = "http://" + serverEndPoint.getIp() + ":" + serverEndPoint.getPort()
				+ serverEndPoint.getBaseAccessUrl() + HESSIAN_ROOT_URL;
		try {
			System.out.println(
					"StubJob    executing the job:appName=" + this.appName + ",jobClass=" + exeParams.getTargetClass());
			JobExecutor jobExecutor = (JobExecutor) factory.create(JobExecutor.class, serverUrl);
			return jobExecutor.execute(exeParams);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		//TODO
		assert false;
		return null;
	}

}
